import React, { useState, useEffect, useMemo, useRef, useContext } from "react";
import { Space, Input, message, notification, Empty, Spin } from "antd";
import { Fragment } from "react-dom";
import "./wechat.scss";
import { SearchOutlined, WindowsFilled } from "@ant-design/icons";
import BraftEditor from "braft-editor";
import "braft-editor/dist/index.css";
import { ContentUtils } from "braft-utils";
import Qs from "qs";
import moment from "moment";
import axios from "axios";
import jwt from "jsonwebtoken";
import { connect } from "react-redux";
import { Scrollbars } from "react-custom-scrollbars";
import replaceImg from "../../utils/replacestr";
import Context from "../Home/Context";
import {throttle} from '../../utils/throttle_debounce'
const getCon = (contents) => {
  return {
    __html: contents,
  };
};
// let ios = null;
const hooks = {
  "toggle-link": ({ href, target }) => {
    const pattern = /^((ht|f)tps?):\/\/([\w-]+(\.[\w-]+)*\/?)+(\?([\w\-.,@?^=%&:/~+#]*)+)?$/;
    if (pattern.test(href)) {
      return { href, target };
    }
    message.warning("请输入完整的正确的网址,必须添加协议头");
    return false;
  },
};
const sayListEle = null;

function Index({ UpateUserInfo, initWebsocket, chatInfo }) {
  // const [left, setLeft] = useState(250);
  const chatcontainer = useRef() ;
  const chatcontentRef = useRef() ;
  // const [top, setTop] = useState(40);
  const [chaLeft, setchaLeft] = useState(0);
  const { state, dispatch, chatRef } = { ...useContext(Context) };
  const [chaTop, setchaTop] = useState(0);
  const [flag, setFlag] = useState(()=> {return false});
  const [chatroomlist, setchatrommList] = useState([]);
  const [users, setUsers] = useState([]);
  const [editorState, seteditorState] = useState(BraftEditor.createEditorState(null));
  const [editorInstance, seteditorInstance] = useState();
  const [flagt, setFlagt] = useState(true);
  const mousedown = function (e) {
    e.persist();
    setFlag((prev) => true);
    setchaLeft((prev) => parseInt(e.clientX - chatcontentRef.current.offsetLeft));
    setchaTop((prev) => parseInt(e.clientY - chatcontentRef.current.offsetTop));
  };
  const mousemove =throttle(function (e) {
    if(!flag) {

      return ;
    }
    e.persist();
    if (flag) {
      // if (e.clientY - chaTop >= -24 && e.clientY - chaTop <= window.innerHeight - 60 - 815) {
        // setTop((prev) => e.clientY - chaTop);
        const chax = Math.max(-25,Math.min(parseInt(e.clientX - chaLeft),parseInt(chatcontainer.current.clientWidth - 1000+26))) ;
        const chay = Math.max(-25,Math.min(parseInt(e.clientY - chaTop),parseInt(window.innerHeight-810-103-24)));
        chatcontentRef.current.style.left = chax  + 'px' ;
        chatcontentRef.current.style.top = chay + 'px' ;

      // if (e.clientX - chaLeft <= window.innerWidth - 24 - 1002 && e.clientX - chaLeft >= -24) {
        // setLeft((prev) => e.clientX - chaLeft);
      // }
    }
  }) ;
  const mouseup = function () {
    // e.persist();
    // console.log('哈哈哈秀秀');
    setFlag((prev) => false);
  };
  const handleEditorChange = function (editor) {
    seteditorState((prev) => editor);
  };
  const getchatroom = async () => {
    let { data: res } = await axios.get("/api/getchatroom", {
      params: {
        userid: UpateUserInfo.userInfo.id,
      },
    });
    if (res.ok !== 1) {
      return message.error(res.message);
    }
    setchatrommList((prev) => res.data);
    let { data: ret } = await axios.get("/api/allusers", {
      params: {
        userid: UpateUserInfo.userInfo.id,
      },
    });
    if (ret.ok !== 1) {
      return message.error(ret.message);
    }
    setUsers((prev) => ret.list);
    let { data: rek } = await axios.get("/api/geteverycurrentword", {
      params: {
        userid: UpateUserInfo.userInfo.id,
      },
    });
    if (rek.ok !== 1) {
      return message.error(rek.message);
    }
    dispatch({
      type: "initlist",
      lastest1: rek.lastest1,
      lastest2: rek.lastest2,
      lastest3: rek.lastest3,
    });
    changeId(1);
  };
  const getroomcontent = async (id) => {
    let { data: res } = await axios.get("/api/chatcontent/" + id, {
      params: {
        userid: UpateUserInfo.userInfo.id,
      },
    });
    if (res.ok != 1) {
      return message.error(res.message);
    }
    dispatch({
      type: "init",
      data: res.list,
    });
  };
  const changeId = async (id) => {
    if (id == state.chatroomid) {
      return;
    }
    seteditorState((prev) => ContentUtils.clear(editorState));
    dispatch({
      type: "chooseId",
      id,
    });
    // setchatRoomId((prev) => id);

    setFlagt((prev) => true);
    let res = chatroomlist.find((item) => item.id == id);
    // setroomname(prev => res.name) ;
    getroomcontent(id);

    setTimeout(() => {
      if (document.querySelector(".sayList")) {
        setFlagt((prev) => false);
        chatRef.current.scrollToBottom();
        chatRef.current.scrollToBottom();
      }
    }, 1000);
  };
  const roomname = useMemo(() => {
    let name = "";
    if (state.chatroomid !== 0 && chatroomlist.length > 0) {
      let res = chatroomlist.find((item) => item.id == state.chatroomid);
      name = res.name;
    }
    return name;
  }, [state.chatroomid]);
  const uploadFnQiNiu = async function (param) {
    const xhr = new XMLHttpRequest();
    let { data: res } = await axios.get("/api/uptoken", {
      params: {
        userid: UpateUserInfo.userInfo.id,
      },
    });
    if (res.ok == 0) {
      return message.error(res.message);
    }
    const formData = new FormData();
    formData.append("file", param.file);
    formData.append("token", res.uptoken);
    formData.append("key", res.key);
    // const result = await fetch("http://up-z2.qiniu.com/", {
    //   method: "post",
    //   body: formData,
    // }).then((response) => response.json());
    // console.log(result) ;
    const successFn = (response) => {
      // 假设服务端直接返回文件上传后的地址
      // 上传成功后调用param.success并传入上传后的文件地址
      let data = JSON.parse(xhr.responseText);
      param.success({
        url: "http://imaegs.chenzefan.xyz/" + data.key,
        meta: {
          id: data.key + "",
          title: "usersmedia" + data.key + "",
          alt: "mdiachenzefan" + data.key,
          loop: false, // 指定音视频是否循环播放
          autoPlay: false, // 指定音视频是否自动播放
          controls: true, // 指定音视频是否显示控制栏
          // poster: false, // 指定视频播放器的封面
        },
      });
    };

    const progressFn = (event) => {
      // 上传进度发生变化时调用param.progress
      param.progress((event.loaded / event.total) * 100);
    };

    const errorFn = (response) => {
      // 上传发生错误时调用param.error
      param.error({
        msg: "上传错误",
      });
    };

    xhr.upload.addEventListener("progress", progressFn, false);
    xhr.addEventListener("load", successFn, false);
    xhr.addEventListener("error", errorFn, false);
    xhr.addEventListener("abort", errorFn, false);

    xhr.open("POST", "http://up-z2.qiniu.com/", true);
    xhr.send(formData);
  };
  const submitComments = async function () {
    let flag = false;
    let flag1 = false;
    editorState.toRAW(true).blocks.forEach((item) => {
      if (item.text.trim(" ") !== "") {
        flag = true;
        return;
      }
    });
    if (chatInfo.isconnected == false) {
      message.error("通讯断开了连接，请重新连接");
      return;
    }
    for (let key in editorState.toRAW(true).entityMap) {
      flag1 = true;
    }
    if (editorState.isEmpty() || (!flag && !flag1)) {
      seteditorState((prev) => ContentUtils.clear(editorState));
      return message.warning("评论内容不可以为空或全为空格");
    } ;
    // console.log(editorState.toHTML().replace(/<[^>]+>/g,""));
    initWebsocket.websocket.emit("chat", {
      content: Qs.stringify({
        comments:  editorState.toRAW(),
        currenttime: moment().unix(),
        id: state.chatroomid,
        token: localStorage.getItem("token"),
        userid: UpateUserInfo.userInfo.id,
        robetword: state.chatroomid === 3 ? editorState.toHTML().replace(/<[^>]+>/g,"") : null 
      }),
    });
    seteditorState((prev) => ContentUtils.clear(editorState));
    return;

    //  message.success(res.message);
  };

  function componentWillUnmount() {
    window.onmouseup = null ;
    dispatch({
      type: "chooseId",
      id: 0,
    });
    dispatch({
      type: "init",
      data: [],
    });
    dispatch({
      type: "initlist",
      lastest1: undefined,
      lastest2: undefined,
      lastest3: undefined,
    });
  }
  // 处理对话信息的时间格式
  const transformtime = (time) => {
    if (moment().format("YYYY") !== moment(time).format("YYYY")) {
      return moment(time).format("YYYY年M月D日 H:mm:ss");
    }
    if (moment().format("YYYY-MM-DD") === moment(time).format("YYYY-MM-DD")) {
      return moment(time).format("H:mm");
    }
    if (moment(time).add(1, "days").format("YYYY-MM-DD") === moment().format("YYYY-MM-DD")) {
      return `昨天 ${moment(time).format("H:mm")}`;
    }
    if (
      moment(time).add(2, "days").format("YYYY-MM-DD") === moment().format("YYYY-MM-DD") ||
      moment(time).add(3, "days").format("YYYY-MM-DD") === moment().format("YYYY-MM-DD") ||
      moment(time).add(4, "days").format("YYYY-MM-DD") === moment().format("YYYY-MM-DD") ||
      moment(time).add(5, "days").format("YYYY-MM-DD") === moment().format("YYYY-MM-DD") ||
      moment(time).add(6, "days").format("YYYY-MM-DD") === moment().format("YYYY-MM-DD")
    ) {
      return `${moment(time).format("dddd")} ${moment(time).format("H:mm")}`;
    }
    return moment(time).format("YYYY年M月D日 H:mm");
  };
  // 处理显示在左侧最新时间的时间格式
  const topcurrentformattime = (time) => {
    if (moment().format("YYYY-MM-DD") === moment(time).format("YYYY-MM-DD")) {
      return moment(time).format("H:mm");
      //  return moment(time).format('YY/MM/D');
    }
    if (moment(time).add(1, "days").format("YYYY-MM-DD") === moment().format("YYYY-MM-DD")) {
      return `昨天`;
    }
    if (
      moment(time).add(2, "days").format("YYYY-MM-DD") === moment().format("YYYY-MM-DD") ||
      moment(time).add(3, "days").format("YYYY-MM-DD") === moment().format("YYYY-MM-DD") ||
      moment(time).add(4, "days").format("YYYY-MM-DD") === moment().format("YYYY-MM-DD") ||
      moment(time).add(5, "days").format("YYYY-MM-DD") === moment().format("YYYY-MM-DD") ||
      moment(time).add(6, "days").format("YYYY-MM-DD") === moment().format("YYYY-MM-DD")
    ) {
      return `${moment(time).format("dddd")}`;
    }
    return moment(time).format("YY/M/D");
  };
  useEffect(() => {
    getchatroom();
      window.onmouseup = mouseup ;
    return componentWillUnmount;
  }, []);
  return (
    <div className="wechat" ref={chatcontainer} >
      <div className="chatcontent" ref={chatcontentRef} style={{left:'373px',top:'0px'}}>
        <div className="slider">
          <div className="imgs">
            <img src="/images/微信.jpg" alt="" />
          </div>
          <div className="chat">
            <img src="/images/chatlight.png" alt="" />
          </div>
          <div className="connectperson">
            <img src="/images/chatperson.png" alt="" />
          </div>
          <div className="extension">
            <img src="/images/extension.png" alt="" />
          </div>
        </div>
        <div className="peoplelist">
          <div className="search">
            <Space size={22}>
              <Input placeholder="搜索" suffix={<SearchOutlined />} />
              <div className="addPerson">+</div>
            </Space>
          </div>
          <div className="outerpeolist">
            <div className="peolist">
              <Scrollbars autoHide autoHideTimeout={1000} autoHideDuration={200}>
                {chatroomlist.length > 0
                  ? chatroomlist.map((item, index) => (
                      <div
                        className="groupitem"
                        key={index}
                        onClick={() => {
                          changeId(item.id);
                        }}
                        style={{ backgroundColor: state.chatroomid == item.id ? "#c5c5c6" : "" }}
                      >
                        <img src="/images/grouppic.jpg" width="50px" height="50px" alt="" />
                        <div className="words" style={{ marginLeft: "12px" }}>
                          <div
                            className="topword"
                            style={{ fontSize: "15px", marginBottom: "5px" }}
                          >
                            {item.name} {item.id === 3 ? '仅自己可见' : ""}
                          </div>
                          <div
                            className="topword"
                            style={{
                              fontSize: "13px",
                              color: "#999999",
                              width: "150px",
                              whiteSpace: "nowrap",
                              textOverflow: "ellipsis",
                              overflow: "hidden",
                              height:'20px',
                              lineHeight:'20px',
                              display:'flex'
                            }}
                          >
                            {state.latestobj[index] !== undefined &&
                            state.latestobj[index] !== "undefined" ? (
                              <>
                                <span style={{
                                     overflow: 'hidden',
                                     whiteSpace: 'nowrap',
                                     textOverflow:' ellipsis',
                                     float: 'left',
                                     flex:2,
                                  }}>{state.latestobj[index].username}</span>：
                                <span
                                  style={{
                                    whiteSpace: 'nowrap',
                                    textOverflow:' ellipsis',
                                    overflow: 'hidden',
                                    float: 'left',
                                    flex:4
                                  }}
                                  className='cutwords'
                                  dangerouslySetInnerHTML={{
                                    __html: replaceImg(
                                      BraftEditor.createEditorState(
                                        new Buffer(state.latestobj[index].content).toString()
                                      ).toHTML()
                                    ),
                                  }}
                                ></span>
                              </>
                            ) : (
                              "暂无信息"
                            )}
                          </div>
                        </div>
                        <div
                          className="rightitem"
                          style={{
                            marginLeft: "15px",
                            position: "relative",
                            fontSize: "13px",
                            color: "#999999",
                            width: "35px",
                          }}
                        >
                          <span style={{display:'none'}}>{chaTop} {chaLeft} {flag}</span>
                          <div
                            className="time"
                            style={{ textAlign: "right", width: "60px", marginLeft: "-24px" }}
                          >
                            {" "}
                            {state.latestobj[index] !== undefined &&
                            state.latestobj[index] !== "undefined" ? (
                              <>{topcurrentformattime(state.latestobj[index].currenttime * 1000)}</>
                            ) : (
                              ""
                            )}
                          </div>
                          <div>
                            <img
                              src="/images/nonote.png"
                              style={{ position: "absolute", bottom: "0", right: "0" }}
                              alt=""
                            />
                          </div>
                        </div>
                      </div>
                    ))
                  : null}
                {users.length > 0
                  ? users.map((item, index) => (
                      <div className="groupitem" key={index}>
                        <img src={item.img} width="50px" height="50px" alt="" />
                        <div className="words" style={{ marginLeft: "12px" }}>
                          <div
                            className="topword"
                            style={{ fontSize: "15px", marginBottom: "5px" }}
                          >
                            {item.username} （模拟）
                          </div>
                          <div
                            className="topword"
                            style={{
                              fontSize: "13px",
                              color: "#999999",
                              width: "150px",
                              whiteSpace: "nowrap",
                              textOverflow: "ellipsis",
                              overflow: "hidden",
                            }}
                          >
                            {item.username}：模拟dom
                          </div>
                        </div>
                        <div
                          className="rightitem"
                          style={{
                            marginLeft: "15px",
                            position: "relative",
                            fontSize: "13px",
                            color: "#999999",
                          }}
                        >
                          <div className="time">00:00</div>
                          <div>
                            <img
                              src="/images/nonote.png"
                              style={{ position: "absolute", bottom: "0", right: "0" }}
                              alt=""
                            />
                          </div>
                        </div>
                      </div>
                    ))
                  : null}
              </Scrollbars>
            </div>
          </div>
        </div>
        <div className="chatroom">
          <div
            className="toptitle"
            onMouseMove={mousemove}
            onMouseDown={mousedown}
          >
            <div
              style={{ fontSize: "23px", marginLeft: "20px", marginTop: "24px" }}
              className="dragarea"
            >
              {roomname} （群名称栏可拖拽）
            </div>
            <div className="more"></div>
          </div>
          <div
            className="mainbody"
            style={{ display: flagt ? "block" : "none", textAlign: "center", lineHeight: "740px" }}
          >
            <Spin size="large">数据加载中</Spin>
          </div>
          <div className="mainbody" style={{ opacity: flagt ? 0 : 1 }}>
            <div className="sayList">
              <Scrollbars ref={chatRef} autoHide autoHideTimeout={1000} autoHideDuration={200}>
                {state.chatList.length > 0 ? (
                  state.chatList.map((item, index) => {
                    return item.userid == UpateUserInfo.userInfo.id  ? (
                      <div key={index}>
                        {index === 0 ||
                        state.chatList[index].currenttime - state.chatList[index - 1].currenttime >
                          2 * 60 ? (
                          <div style={{ display: "flex", height: "50px", alignItems: "center" }}>
                            <div className="time" style={{ textAlign: "center", margin: "0 auto" }}>
                              {transformtime(item.currenttime * 1000)}
                            </div>
                          </div>
                        ) : null}
                        <div className="me">
                          <img
                            src={UpateUserInfo.userInfo.img}
                            width="40px"
                            height="40px"
                            style={{ borderRadius: "4px" }}
                            alt=""
                          />
                          <div className="myword">
                            <p
                              className="mysay"
                              dangerouslySetInnerHTML={getCon(
                                BraftEditor.createEditorState(
                                  new Buffer(item.content).toString()
                                ).toHTML()
                              )}
                            ></p>
                          </div>
                        </div>
                      </div>
                    ) : (
                      <div key={index}>
                        {index === 0 ||
                        state.chatList[index].currenttime - state.chatList[index - 1].currenttime >
                          2 * 60 ? (
                          <div style={{ display: "flex", height: "50px", alignItems: "center" }}>
                            <div className="time" style={{ textAlign: "center", margin: "0 auto" }}>
                              {transformtime(item.currenttime * 1000)}
                            </div>
                          </div>
                        ) : null}
                        <div className="other" key={index}>
                          <img
                            src={item.img}
                            width="40px"
                            height="40px"
                            style={{ borderRadius: "4px", marginRight: "12px" }}
                            alt=""
                          />
                          <div className="myword">
                            <p className="othername">{item.username}</p>
                            <p
                              className="mysay"
                              dangerouslySetInnerHTML={getCon(
                                BraftEditor.createEditorState(
                                  new Buffer(item.content).toString()
                                ).toHTML()
                              )}
                            ></p>
                          </div>
                        </div>
                      </div>
                    );
                  })
                ) : (
                  <Empty style={{ marginTop: "150px" }} />
                )}
              </Scrollbars>
            </div>
          </div>
          <div className="sendmessage" style={{ display: flagt ? "none" : "block" }}>
            <BraftEditor
              hooks={hooks}
              media={{
                uploadFn: uploadFnQiNiu,
                accepts: {
                  image: "image/png,image/jpeg,image/gif,image/webp,image/apng,image/svg",
                  video: false,
                  audio: false,
                },
                externals: {
                  image: "image/png,image/jpeg,image/gif,image/webp,image/apng,image/svg",
                  video: false,
                  audio: false,
                  embed: false,
                },
              }}
              ref={(instance) => seteditorInstance((prev) => instance)}
              value={editorState}
              onChange={handleEditorChange}
              controls={["emoji", "italic", "text-color", "link", state.chatroomid !== 3 ?"media":'', "clear"]}
            ></BraftEditor>
          </div>
          <div
            className="sendbtn"
            onClick={submitComments}
            style={{ display: flagt ? "none" : "block" }}
          >
            发送(S)
          </div>
        </div>
      </div>
    </div>
  );
}

export default connect(
  (state) => state,
  (dispatch) => {
    return {
      changeContent: (data) => dispatch(data),
    };
  }
)(Index);
